package com.yitiao.multithread.threadnotify;

import java.util.ArrayList;
import java.util.List;

/**
 * @author libiao
 */
public class ThreadNotifyWait {
    //定义共享变量来实现通信，它需要volatile修饰，否则线程不能及时感知
    static volatile boolean notice = false;

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Object obj = new Object();

        new Thread(() -> {
            while (true) {
                synchronized (obj) {
                    if (list.size() != 5) {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("线程B收到通知，开始执行自己的业务...");
                    try {
                        obj.notify();
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();

        //线程A
        new Thread(() -> {
            synchronized (obj){
                for (int i = 1; i <= 10; i++) {
                    list.add("abc");
                    System.out.println("线程A添加元素，此时list的size为：" + list.size());
                    if (list.size() == 5) {
                        obj.notify();
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}
